from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer
from App.models import User, UserLike


class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class UserLikeSerializer(ModelSerializer):
    """粉丝关注数表序列化器"""
    target_user = SerializerMethodField()
    class Meta:
        model = UserLike
        # 返回的字段
        exclude = ('created_time', 'user', 'status')

    def get_target_user(self, obj):
        # 根据上下文判断是序列化关注者还是被关注者
        context = self.context
        is_fans_list = context.get('is_fans_list', False)
        if is_fans_list:
            # 如果是粉丝列表，展示被关注者的信息和粉丝数
            user = obj.user
            fans_count = UserLike.objects.filter(user=user, status=True).count()
        else:
            # 如果是关注列表，展示关注者的信息和关注数
            user = obj.target_user
            fans_count = UserLike.objects.filter(user=user, status=True).count()
        # 格式化粉丝数
        if fans_count >= 10000:
            fans_count = str(round(fans_count / 10000, 1)) + '万'
        return {
            'fans_count': fans_count,
            'user_id': user.id,
        }
    def to_representation(self, instance):
        # 传递额外的上下文信息给get_user_info方法
        self.context['is_fans_list'] = self.context.get('is_fans_list', False)
        return super().to_representation(instance)






